package org.scboy.dbms.service.imp;

import java.util.List;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.dbms.dao.InterCodeDao;
import org.scboy.dbms.dao.InterMsgDao;
import org.scboy.dbms.service.InterService;
import org.scboy.utils.caches.dbms.entity.InterEntity;
import org.scboy.utils.entitys.coobi.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;

@Service
public class InterServiceImpl implements InterService {

	@Autowired
	EntityFactory factory;
	
	@Override
	public void initInter(List<InterEntity> inters) {
		
		InterCodeDao codeDao=factory.getDao(InterCodeDao.class);
		
		InterMsgDao msgDao=factory.getDao(InterMsgDao.class);
		
		for (InterEntity inter : inters) {
			
			//检查CODE是否存在,并初始化。
			String codeId=MD5.create().digestHex(inter.getAppName()+"-"+inter.getCode());
			if(codeDao.count(Model.create().add("id", codeId))==0) {
				Model data=Model.create();
				data.add("id", codeId);
				data.add("code", inter.getCode());
				data.add("msgName", StrUtil.isEmpty(inter.getName())? inter.getCode() : inter.getName());
				data.add("codeState", 1);
				data.add("appName", inter.getAppName());
				codeDao.insert(data);
			}
			
			//检查默认消息是否存在
			if(msgDao.count(Model.create().add("codeId", codeId).add("lang", inter.getLang()))==0) {
				Model data=Model.create();
				data.add("id", UUID.randomUUID().toString());
				data.add("codeId", codeId);
				data.add("lang", inter.getLang());
				data.add("msg", inter.getMsg());
				msgDao.insert(data);
			}
		}
	}

	@Override
	public InterEntity getInter(String appName,String code,String lang) {

		InterCodeDao codeDao=factory.getDao(InterCodeDao.class);
		
		InterMsgDao msgDao=factory.getDao(InterMsgDao.class);
		
		InterEntity InterEntity=new InterEntity();
		InterEntity.setAppName(appName);
		InterEntity.setCode(code);
		InterEntity.setLang(lang);
		
		Model codeModel=codeDao.get(Model.create().add("appName", appName).add("code", code).addRc("id"));
		
		if(codeModel!=null) {
			Model langModel=msgDao.get(Model.create().add("codeId", codeModel.getString("id")).add("lang", lang).addRc("msg"));
			if(langModel!=null) {
				InterEntity.setMsg(langModel.getString("msg"));
				return InterEntity;
			}else {
				return null;
			}
		}else {
			return null;
		}
	}
	
}
